package com.example.myapplication16_1;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {

    private TextView responseText;
    private Button connectButton;
    private Handler handler;

    // 服务器相关配置
    private static final String SERVER_IP = "192.168.2.51"; // 使用模拟器时，这个IP对应电脑上的localhost
    private static final int SERVER_PORT = 8888; // 与服务器端口一致

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化控件
        responseText = findViewById(R.id.responseText);
        connectButton = findViewById(R.id.connectButton);

        // 初始化Handler用于在UI线程更新界面
        initHandler();

        // 设置按钮点击事件
        connectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 点击按钮后，显示连接中...
                responseText.setText("正在连接服务器...");
                connectButton.setEnabled(false);
                
                // 步骤四：创建并启动一个线程
                new Thread(new ClientThread()).start();
            }
        });
    }

    // 初始化Handler
    private void initHandler() {
        handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                // 步骤七：使用Handler更新UI
                if (msg.what == 1) {
                    String serverResponse = (String) msg.obj;
                    responseText.setText(serverResponse);
                } else if (msg.what == 0) {
                    // 连接失败
                    String errorMsg = (String) msg.obj;
                    responseText.setText("连接失败: " + errorMsg);
                    Toast.makeText(MainActivity.this, "连接服务器失败", Toast.LENGTH_SHORT).show();
                }
                
                // 恢复按钮可点击状态
                connectButton.setEnabled(true);
            }
        };
    }

    // 客户端线程
    private class ClientThread implements Runnable {
        @Override
        public void run() {
            Socket socket = null;
            BufferedReader reader = null;
            Message message = handler.obtainMessage();
            
            try {
                // 步骤五：创建Socket对象连接服务器
                socket = new Socket(SERVER_IP, SERVER_PORT);

                // 设置超时时间
                socket.setSoTimeout(5000);

                // 步骤六：通过Socket读取服务器返回的数据
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String response = reader.readLine();
                
                // 读取成功，发送消息给Handler
                message.what = 1;
                message.obj = response;
                
            } catch (IOException e) {
                // 发生异常，发送错误消息给Handler
                message.what = 0;
                message.obj = e.getMessage();
                e.printStackTrace();
            } finally {
                // 关闭资源
                try {
                    if (reader != null) reader.close();
                    if (socket != null) socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                
                // 发送消息给Handler更新UI
                handler.sendMessage(message);
            }
        }
    }
}